package com.ikangtai.shecare.common.services.ble;


import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.eventBusMsg.BatteryVolumeMsg;
import com.ikangtai.shecare.common.eventBusMsg.ConnectStateMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.main.MainActivity;

import org.simple.eventbus.EventBus;

import java.text.DecimalFormat;

public class BLEBroadcastReceiver extends BroadcastReceiver{

    private boolean mConnected = false;// 连接
    private int scanSign = 0;

    @Override
    public void onReceive(final Context context, Intent intent) {

        String action = intent.getAction();
        AppLog.e("onReceive action=" + action);


        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                    BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    AppLog.e("STATE_OFF 手机蓝牙关闭");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    AppLog.e("STATE_TURNING_OFF 手机蓝牙正在关闭");
                    break;
                case BluetoothAdapter.STATE_ON:
                    AppLog.e("STATE_ON 手机蓝牙开启");
                    ((MainActivity)context).operateThermometerScan(true);// 温度计扫描操作打开
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    AppLog.e("STATE_TURNING_ON 手机蓝牙正在开启");
                    break;
            }
        }

        if (BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName().equals(action)) {// 如果找到温度计的信息与程序定义的温度计信息一致
        }
        if (BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED.getName().equals(action)) {// 连接成功
            updateConnectInfo(context);
        } else if (BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED.getName()
                .equals(action)) {// 断开连接温度计
            AppLog.e("THERMOMETER_DISCONNECTED");
            updateDisconnectInfo(context);
        } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_FOUND.getName()
                .equals(action)) {
        } else if (BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_FOUND
                .getName().equals(action)) {
        } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_TYPE_FOUND.getName()
                .equals(action)) {
        } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND.getName()
                .equals(action)) {
//                handleTimeSyncResult(intent);
        } else if (BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND.getName()
                .equals(action)) {
            handleBatteryVolume(intent);
        } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN.getName()
                .equals(action)) {
            AppLog.e("TEMPERATURE_MEASUREMENT_OPEN");
            if (!App.isBindActivityActive && !App.isMyDeviceActivityActive) {
                ((MainActivity)context).mBLEThermometerService.getBatteryVolume();
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        ((MainActivity)context).mBLEThermometerService.syncCurrentTime();
                    }
                }, 200);
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        ((MainActivity)context).sendPregnantPeriod();
                    }
                }, 500);
            }
//                mBLEThermometerService.readFirmwareRevision();
        } else if (BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ.getName().equals(action)) {
//                String hardwareVersion = intent.getStringExtra(BLEThermometerService.ThermometerDataTag.FIRMWARE_REVISION_DATA.getName());
//                AppLog.e("FIRMWARE_REVISION_READ" + hardwareVersion);
        } else if (BLEThermometerService.ThermometerMessage.MEASUREMENT_INTERVAL_FOUND.getName()
                .equals(action)) {
            AppLog.e("MEASUREMENT_INTERVAL_FOUND");
        } else if (BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ.getName()
                .equals(action)) {
            handleTemperatureResult(context, intent);
        } else if (BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                .getName().equals(action)) {
            //operateThermometerScan(true);
        }
    }

    private void handleTemperatureResult(final Context context, Intent intent) {
        BLEThermometerService.TemperatureUnit unit = (BLEThermometerService.TemperatureUnit) intent
                .getSerializableExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_UNIT_DATA
                        .getName());
        int Thermometer_flag = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_FLAG.getName(), 0);
        int year = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_YEAR.getName(), 0);
        int month = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MONTH.getName(), 0);
        int day = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_DAY.getName(), 0);
        int hour = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_HOUR.getName(), 0);
        int min = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MIN.getName(), 0);
        final int num = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_NUM_DATA.getName(), 0);
        double temperature = intent.getDoubleExtra(BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA.getName(), 0.0f);
        DecimalFormat df = new DecimalFormat("0.00");
        String time = year + "-" + month + "-" + day + " " + hour + ":" + min + ":00";
        if (Thermometer_flag == 0) {
            AppLog.e("Thermometer_flag---" + Thermometer_flag + "thermometer---" + temperature + "day---" + day);
            //处理1代和2代离线温度（不含最后1条）
            ((MainActivity)context).saveTemperatureData2List(String.valueOf(df.format(temperature)), time);

        } else if (Thermometer_flag == 1) {

            AppLog.e("Thermometer_flag---" + Thermometer_flag + "thermometer---" + temperature + "day---" + day);
            //处理1代和2代最后1条离线温度
            //Toast.makeText(MainActivity.this, R.string.bbt_post_start, Toast.LENGTH_SHORT).show();
            ((MainActivity)context).saveTemperatureData2List(String.valueOf(df.format(temperature)), time);
            if (num >= 0) {
                ((MainActivity)context).filterSameTemper();
                ((MainActivity)context).mBLEThermometerService.syncACKTemperatureNum(((MainActivity)context).temperatureInfoList.size());
            }
            //isTemperFinish = true;
            ((MainActivity)context).numFlag1++;
            if (((MainActivity)context).numFlag1 == 1) {
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                            ((MainActivity)context).showProgressDialog();

                        ((MainActivity)context).filterTempWithValidTime();
                        ((MainActivity)context).filterTemperatureforSync();

                        if (((MainActivity)context).syncTemperatureInfoList.size() > 0) {
                            if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                                //Toast.makeText(MainActivity.this, R.string.bbt_post_success, Toast.LENGTH_LONG).show();
                                if (((MainActivity)context).syncTemperatureInfoList.size() > 0) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            ((MainActivity)context).syncAndUploadRecordDatas();
                                        }
                                    }).start();
                                }

                        } else {
                            ((MainActivity)context).dissmissProgressDiaLog();
                        }
                        if (((MainActivity)context).THERMOMETER_CONNECTED_END_NUM == 0) {
                            ((MainActivity)context).THERMOMETER_CONNECTED_END_NUM = ((MainActivity)context).THERMOMETER_CONNECTED_END_NUM + 1;
                            ((MainActivity)context).THERMOMETER_CONNECTED_NUM = 0;
                        }
                        ((MainActivity)context).numFlag1 = 0;
                    }

                }, 1000);
            }

        } else if (Thermometer_flag == 2) {
            AppLog.e("hxiao flag 2");
            //处理1代在线测量得到的数据
            //Toast.makeText(MainActivity.this, R.string.bbt_post_start, Toast.LENGTH_SHORT).show();
            //saveTemperatureData(String.valueOf(df.format(temperature)), time);
            ((MainActivity)context).saveTemperatureData2List(String.valueOf(df.format(temperature)), time);
            (new Handler()).postDelayed(new Runnable() {
                @Override
                public synchronized void run() {
                    if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                        ((MainActivity)context).showProgressDialog();
                    ((MainActivity)context).filterSameTemper();
                    ((MainActivity)context).filterTempWithValidTime();
                    ((MainActivity)context).filterTemperatureforSync();
                    if (((MainActivity)context).syncTemperatureInfoList.size() > 0) {
                        if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                            //Toast.makeText(MainActivity.this, R.string.bbt_post_success, Toast.LENGTH_LONG).show();
                            if (((MainActivity)context).syncTemperatureInfoList.size() > 0) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        ((MainActivity)context).syncAndUploadRecordDatas();
                                    }
                                }).start();
                            }
                    } else {
                        ((MainActivity)context).dissmissProgressDiaLog();
                    }
                }
            }, 1000);

        }
    }

    private void handleBatteryVolume(Intent intent) {
        float result = intent.getFloatExtra(BLEThermometerService.ThermometerDataTag.CLOSE_THERMOMETER_DATA.getName(), 0);
        AppLog.e("batteryVolume:" + result);
        BatteryVolumeMsg batteryVolumeMsg = new BatteryVolumeMsg();
        if (result >= 72.25 && result <= 74) {
            batteryVolumeMsg.setRespCode(5);
        }
        if (result >= 70.5 && result < 72.25) {
            batteryVolumeMsg.setRespCode(4);
        }
        if (result >= 68.75 && result < 70.5) {
            batteryVolumeMsg.setRespCode(3);
        }
        if (result >= 67 && result < 68.75) {
            batteryVolumeMsg.setRespCode(2);
        }
        if (result < 67) {
            batteryVolumeMsg.setRespCode(1);
        }
        if (result > 10)
            EventBus.getDefault().post(batteryVolumeMsg);
    }

    private void updateDisconnectInfo(final Context context) {
        mConnected = false;
        ((MainActivity)context).THERMOMETER_CONNECTED_NUM = 0;
        ((MainActivity)context).THERMOMETER_CONNECTED_END_NUM = 0;

        if (null != App.memory_preference_macAddress && !"".equals(App.memory_preference_macAddress)) {
            ConnectStateMsg connectStateMsg = new ConnectStateMsg();
            connectStateMsg.setRespCode(0);
            EventBus.getDefault().post(connectStateMsg);
        }
        if (!App.isBindActivityActive && !App.isMyDeviceActivityActive) {
            if (scanSign == 0) {
                scanSign = 1;
                (new Handler()).postDelayed(new Runnable() {
                    @Override
                    public synchronized void run() {
                        scanSign = 0;
                        ((MainActivity)context).operateThermometerScan(true);// 温度计扫描操作打开
                    }
                }, ((MainActivity)context).SCAN_PERIOD);
                AppLog.e("THERMOMETER_DISCONNECTED postDelayed operateThermometerScan");
            }
        }
    }

    private void updateConnectInfo(final Context context) {
        ((MainActivity)context).numFlag1 = 0;
        mConnected = true;
        ((MainActivity)context).saveConnectTime();
        ((MainActivity)context).temperatureInfoList.clear();
        ((MainActivity)context).syncTemperatureInfoList.clear();
        ((MainActivity)context).syncRecordDataList.clear();
        if (((MainActivity)context).THERMOMETER_CONNECTED_NUM == 0) {

            if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                Toast.makeText(context, context.getString(R.string.hardware_attach), Toast.LENGTH_LONG).show();
            if (null != App.memory_preference_macAddress && !"".equals(App.memory_preference_macAddress)) {
                ConnectStateMsg connectStateMsg = new ConnectStateMsg();
                connectStateMsg.setRespCode(1);
                EventBus.getDefault().post(connectStateMsg);
            }
            ((MainActivity)context).THERMOMETER_CONNECTED_NUM = ((MainActivity)context).THERMOMETER_CONNECTED_NUM + 1;
        } else {
            ((MainActivity)context).THERMOMETER_CONNECTED_NUM = ((MainActivity)context).THERMOMETER_CONNECTED_NUM + 1;
        }
    }

//        private void handleTimeSyncResult(Intent intent) {
//            int result = intent.getIntExtra(BLEThermometerService.ThermometerDataTag.SYNC_TIME_DATA.getName(), 0);
//            if (1 == result)
//                Toast.makeText(CalendarActivity.this, "同步时间成功！", Toast.LENGTH_LONG).show();
//            if (2 == result)
//                Toast.makeText(CalendarActivity.this, "同步时间失败！", Toast.LENGTH_LONG).show();
//        }
}
